package hackathon.att.atl.android.autoresponder;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.QuickContactBadge;

public class MainActivity extends Activity {
	private static final int CONTACT_PICKER_RESULT = 1;
	
	private Uri contactUri;
	private AutoResponderDAO dao = new AutoResponderDAO(this);
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void chooseContact(View view){
    	Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,  
                Contacts.CONTENT_URI);  
        startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (resultCode == RESULT_OK && requestCode == CONTACT_PICKER_RESULT) {  
        	contactUri = data.getData();
        	((QuickContactBadge)findViewById(R.id.quickContactBadge1)).assignContactUri(contactUri);
        } else {  
            // gracefully handle failure  
            Log.e("Android AutoResponder", "Error: could not find contact");  
        }  
    }
    
    public void saveAlert(View view){
    	String message = ((EditText)findViewById(R.id.editText1)).getText().toString();
    	boolean includeLocation = ((CheckBox)findViewById(R.id.checkBox1)).isChecked();
    	String phoneNumber = getPhoneNumber();
    	
    	AutoResponderData data = new AutoResponderData();
    	
    	data.setContact_uri(contactUri.toString());
    	data.setGetLocationFlag(includeLocation);
    	data.setPhoneNumber(phoneNumber);
    	data.setText_msg(message);
    	
    	dao.open();
    	dao.updateContactInfo(data);
    	dao.close();
    }

    private String getPhoneNumber(){
    	Cursor cursor = getContentResolver().query(  
    	        Phone.CONTENT_URI, null,  
    	        Phone.CONTACT_ID + "=?",  
    	        new String[]{contactUri.getLastPathSegment()}, null);
    	
    	cursor.moveToFirst();
    	
    	int numberIdx = cursor.getColumnIndex(Phone.DATA);  
        String number = cursor.getString(numberIdx);
        return number;
    }

	@Override
	protected void onPause() {
		super.onPause();
		dao.close();
	}
    
    
}
